# -*- coding: utf-8 -*-
from django.utils.translation import ugettext as _
from django.db import models
from django.core.exceptions import ObjectDoesNotExist

POST_STATUS = (   
    ('publish', _('Published')),
    ('draft', _('Draft')),
    ('private', _('Private')),
)

class Category(models.Model):
    category_name = models.CharField(verbose_name=_('category_name'),max_length=100)
    category_desc = models.CharField(verbose_name=_('category_desc'),max_length=1024)

    def __unicode__(self):
        return '%s' % self.category_name

    def get_absolute_url(self):
        return "/blog/category/%s/" % self.id

    class Meta:
        verbose_name = _('Category')
        verbose_name_plural = _('Categories')
    
    class Admin:
        list_display = ('id', 'category_name')

def get_or_create_tag(tag_name):
    try:
        tag = Tag.objects.get(tag_name=tag_name)
    except ObjectDoesNotExist:
        tag = Tag(tag_name=tag_name,postCount=1)
    return tag

def save_or_del_tag(oldtaglist,tags=[]):
    for temp in oldtaglist:
        if temp not in tags and temp != '':
            t = get_or_create_tag(temp)
            t.postCount = t.postCount - 1
            if t.postCount <= 0:
                t.delete()
            else:
                t.save()

def edit_or_new_tags(tags,self,oldtags=''):
    for tag in tags:
        if tag != '':
            tag_object = get_or_create_tag(tag)
            if oldtags.find(tag_object.tag_name) == -1:
	           tag_object.postCount = tag_object.postCount + 1
            tag_object.save()
            if oldtags.find(tag_object.tag_name) == -1:
				tag_object.posts.add(self)

class Post(models.Model):
    category = models.ForeignKey(Category,verbose_name=_('Category'))
    title = models.CharField(verbose_name=_('title'),max_length=200)
    content = models.TextField(verbose_name=_('content'))
    status = models.CharField(verbose_name=_('status'),max_length=10,default='publish',choices = POST_STATUS)
    tags = models.CharField(verbose_name=_('tags'),max_length=200)
    pubdate = models.DateTimeField(verbose_name=_('pubdate'))

    def __unicode__(self):
        return '%s' % self.title 

    def get_absolute_url(self):
        return "/blog/%i/" % self.id

    def save(self):
        oldtags = ''
        tags = self.tags.split(',')
        if self.id != None:
            oldtags = Post.objects.get(id=self.id).tags
            oldtaglist = oldtags.split(',')
            save_or_del_tag(oldtaglist,tags)
        super(Post, self).save()
        edit_or_new_tags(tags,self,oldtags)

    def delete(self):
        tags = self.tags.split(',')
        save_or_del_tag(tags)
        super(Post, self).delete()

    class Meta:
        verbose_name = _('Post')
        verbose_name_plural = _('Posts')
    

    class Admin:
        js = ('/editor/jquery.js','/editor/wymeditor/tiny_mce.js','/editor/admin_textarea.js')
        list_display = ('title','content','status','pubdate')
        list_filter = ('pubdate',)
        search_fields = ['title','content',]


class Tag(models.Model):
    tag_name = models.CharField(verbose_name=_('tag_name'),max_length=100)
    posts = models.ManyToManyField(Post,verbose_name=_('posts'))
    postCount = models.IntegerField(verbose_name=_('postCount'))

    def __unicode__(self):
        return self.tag_name

    def get_absolute_url(self):
        return "/tag/%i/" %self.id

    class Meta:
        verbose_name = _('Tag')
        verbose_name_plural = _('Tags')
    
    class Admin:
        list_display = ('tag_name','postCount')
        search_fields = ['tag_name',]

class Comment(models.Model):
    post = models.ForeignKey(Post,verbose_name=_('post'))
    comment_author = models.CharField(verbose_name=_('comment_author'),max_length=20)
    comment_email = models.EmailField(verbose_name=_('comment_email'),max_length=100,default='wglin122@gmail.com')
    comment_url = models.URLField(verbose_name=_('comment_url'),default='http://www.sina.com.cn')
    comment_content = models.TextField(verbose_name=_('comment_content'))
    comment_time = models.DateTimeField(verbose_name=_('comment_time'),auto_now=True)

    def __unicode__(self):
        return '%s' % self.comment_author

    def get_absolute_url(self):
        return "/blog/%i/#comment-%i" % (self.post.id,self.id)

    class Meta:
        verbose_name = _('Comment')
        verbose_name_plural = _('Commentes')

    class Admin:
        list_display = ('comment_author', 'comment_time', 'comment_content','comment_email','del_Comment',)
        list_filter = ('comment_time',)
        search_fields = ['post__title',]
    
    def del_Comment(self):
        return '<a href="%s/delete/">删除</a>'%self.id
    del_Comment.short_description = '删除评论'
    del_Comment.allow_tags = True

class Link(models.Model):
    link_name = models.CharField(verbose_name=_('link_name'),max_length=50)
    link_address = models.URLField(verbose_name=_('link_address'))

    def __unicode__(self):
        return '%s' % self.link_name
  
    class Meta:
        verbose_name = _('Link')
        verbose_name_plural = _('Links')

    class Admin:
        list_display = ('link_name', 'link_address')

class Widget_Model(models.Model):
    model_name = models.CharField(verbose_name=_('model_name'),max_length=50)
    model_file = models.CharField(verbose_name=_('model_file'),max_length=50)

    def __unicode__(self):
        return '%s' % self.model_name

    class Meta:
      verbose_name = _('Widget_Model')
      verbose_name_plural = _('Widget_Models')

    class Admin:
      list_display = ('model_name', 'model_file')

class Widget(models.Model):
    widgetModels = models.ManyToManyField(Widget_Model,verbose_name=_('widgetModels'))

    def __unicode__(self):
        return 'widget'
  
    class Meta:
        verbose_name = _('Widget')
        verbose_name_plural = _('Widgets')

    class Admin:
        list_display = ('showWidget',)

    def showWidget(self):
        wm = self.widgetModels.all()
        show = ''
        for w in wm:
            show = show + '%s,'%w
        return show[:-1]
    showWidget.short_description = '组件'
    showWidget.allow_tags = True
'''
'''